import { t } from 'i18next'
import React, { FC } from 'react'
import {
	Wrap,
	IconChairmanAvatar,
	IconSpeakerAvatar,
	IconCancelChairman,
	IconChairmanPoll,
	IconMtVmp,
	IconChairmanSelectView,
	IconCancelChairmanSelectView,
	IconCancelDoubleFlow,
	IconDoubleFlow,
	IconCancelSpeaker,
	IconsWrap,
	ManagerWrap,
} from './style'
import { Droppable, Draggable, DragDropContextProvider } from '@/plugins/dnd'
import { ListItemGhost } from '../../../components'
import { useMccStore } from '@/pages/manager/store'
import useLock from '@/hooks/useLock'
import {
	fetchStartDoubleFlow,
	fetchStopDoubleFlow,
	fetchSetChairman,
	fetchSetSpeaker,
	fetchCancelChairman,
	fetchCancelSpeaker,
	fetchChairmanVmp,
} from '@/api/manager/actions'
import Alert, { Confirm, confirmModal } from '@/components/Alert'
import { useManagerStore } from './store'
import { Mt, revert_mt } from '@/api/manager/mt'
import { DropData, IMcc } from '@/api/manager/type'
import { Meeting, revert_meeting } from '@/api/manager/meeting'
import shallow from 'zustand/shallow'
import { store as SmsStore } from '@/pages/manager/blocks/sms/store'
import { useMonitorStore } from '../../monitor/store'
import { usePlayVideoStore } from '../../playVideo/store'
import { useParamsStore } from '../store'
import { usePollStore } from '../../poll/store'
import { fetchGetVmpParams } from '@/api/manager/vmp'
import { Modal } from '@kedacom/react-next'
import { useVmpTypeStore } from '../../vmp/store.get'
import { useVmpStore } from '../../vmp/store'
import { useTableAllStore } from '../table/all/store'
import { getItemInTree } from '../table/all/utils'
import { useMtVmpStore } from '../../mtVmp/store'
const ManagerChairmanIcons: FC<{ chairman: Mt }> = ({ chairman }) => {
	const meetingType = useMccStore((state) => state.mccInfo.meetingType)
	const meetingMoid = useMccStore((state) => state.mccInfo.meetingMoid)
	const chairmanSelectView = useManagerStore((state) => state.isChairmanSelectView)
	const handleCancelChairman = useLock(async () => {
		const isMeetingAdminOrCreator = useMccStore.getState().isMeetingAdminOrCreator
		if (isMeetingAdminOrCreator) {
			await fetchCancelChairman(meetingMoid, chairman).then((res) => {
				if (res && res.success) {
					SmsStore.getState().updateList([revert_mt(chairman)])
				}
			})
		} else {
			Confirm(t('若取消自己管理方，您将失去管理方权限'), () => fetchCancelChairman(meetingMoid, chairman))
		}
	})
	const handleOpenChairmanPoll = () => {
		useMccStore.getState().setCurPage('chairman_poll')
		useParamsStore.getState().showActionButton()
		usePollStore.getState().update({ poll_mode: 2 })
	}
	const handleCloseChairmanSelectView = () => {
		fetchChairmanVmp(meetingMoid, chairman.mtid, 0)
	}
	const handleOpenChairmanSelectView = () => {
		fetchGetVmpParams(meetingMoid).then((res) => {
			if (res.success) {
				if (res.data?.state) {
					//开启画面合成
					if (res.data.broadcast) {
						//开启广播
						Alert(t('会议已开启会议画面合成广播,无需重复选看'))
					} else {
						fetchChairmanVmp(meetingMoid, chairman.mtid, 1)
					}
				} else {
					//未开启画面合成
					confirmModal({
						width: 440,
						height: 300,
						msg: (
							<div style={{ fontSize: 14 }}>
								{t('会议画面合成未开启')}
								<br />
								{t('请开启会议画面合成，并关闭广播，再选看画面合成')}.
							</div>
						),
						okText: t('会议画面合成'),
						onOk: () => {
							useVmpTypeStore.setState({ type: 'vmp' })
							useVmpStore.setState({
								isOpen: true,
								isShowPlanOperateModal: false,
								onClose: () => {
									useMccStore.getState().setCurPage('mcc_main')
								},
							})
							useMccStore.getState().setCurPage('vmp')
						},
					})
				}
			} else {
				Alert(res.description || t('操作失败'))
			}
		})
	}
	const handleOpenMtVmpDialog = () => {
		// rxMainOut.effect.openMtVmpDialog(chairman)
		if (chairman && chairman.mtKey) {
			const tableAll = useTableAllStore.getState().tree
			const batchMembers: Mt[] = []
			getItemInTree(tableAll, (item) => {
				if (
					item.mcc.confLevel === 2 &&
					item.mcc.isMt &&
					item.mcc.status.isOnline &&
					item.mcc.mtType !== 7 &&
					item.mcc.mtType !== 9
				) {
					batchMembers.push(new Mt(revert_mt(item.mcc)))
				}
			})
			useVmpTypeStore.setState({ type: `mtVmp_${chairman.mtKey}` })
			useMtVmpStore.setState({
				isOpen: true,
				isShowPlanOperateModal: false,
				batchMembers,
				mt_info: chairman,
				onClose: () => {
					useMccStore.getState().setCurPage('mcc_main')
				},
			})
			useMccStore.getState().setCurPage('mtvmp')
		}
	}
	return (
		<IconsWrap>
			<div className="action-icons">
				<IconCancelChairman title={t('释放管理方')} className="icon" onClick={handleCancelChairman} />
				{meetingType !== 2 && (
					<>
						<IconChairmanPoll title={t('管理方轮询')} className="icon" onClick={handleOpenChairmanPoll} />
						{meetingType === 0 ? (
							chairmanSelectView ? (
								<IconCancelChairmanSelectView
									title={t('取消管理方选看画面合成')}
									className="icon"
									onClick={handleCloseChairmanSelectView}
								/>
							) : (
								<IconChairmanSelectView
									title={t('开启管理方选看画面合成')}
									className="icon"
									onClick={handleOpenChairmanSelectView}
								/>
							)
						) : (
							<IconMtVmp title={t('管理方画面合成')} className="icon" onClick={handleOpenMtVmpDialog} />
						)}
					</>
				)}
			</div>
		</IconsWrap>
	)
}
const ManagerSpeakerIcons: FC<{ speaker: IMcc }> = ({ speaker }) => {
	const meetingMoid = useMccStore((state) => state.mccInfo.meetingMoid)
	const handleCancelSpeaker = useLock(async () => {
		await fetchCancelSpeaker(meetingMoid, speaker).then((res) => {
			if (res && res.success) {
				if (speaker.isMt) SmsStore.getState().updateList([revert_mt(speaker)])
			}
		})
	})
	const handleDoubleFlow = useLock(async () => {
		speaker.status.isDoubleFlow
			? await fetchStopDoubleFlow(meetingMoid, speaker)
			: await fetchStartDoubleFlow(meetingMoid, speaker)
	})
	return (
		<IconsWrap>
			<div className="action-icons">
				<IconCancelSpeaker title={t('释放发言方')} className="icon" onClick={handleCancelSpeaker} />
				{speaker.status.isDoubleFlow ? (
					<IconCancelDoubleFlow title={t('取消内容共享')} className="icon" onClick={handleDoubleFlow} />
				) : (
					<IconDoubleFlow title={t('开启内容共享')} className="icon" onClick={handleDoubleFlow} />
				)}
			</div>
		</IconsWrap>
	)
}
export const Manager: FC = () => {
	const meetingMoid = useMccStore((state) => state.mccInfo.meetingMoid)
	const { chairman, speaker } = useManagerStore(
		(state) => ({ chairman: state.chairman, speaker: state.speaker }),
		shallow
	)
	const handleDropChairman = useLock(async (dataTransfer: DropData) => {
		if (dataTransfer && dataTransfer.data && dataTransfer.data.mt) {
			let mt = dataTransfer.data.mt
			if (chairman) {
				if (mt.mt_key === chairman.mtKey) {
					return
				}
			}
			if (mt.mt_key === '0.0.0.0_0') {
				return
			}
			if (mt.conf_level === 1 || mt.conf_level === 3 || !mt.isMt) {
				Alert(t('只能设置本级终端为管理方'))
				return
			}
			if (mt.mt_type === 9) {
				Alert(t('简单级联会议不能设为管理方'))
				return
			}
			const isMeetingAdminOrCreator = useMccStore.getState().isMeetingAdminOrCreator
			if (isMeetingAdminOrCreator) {
				await fetchSetChairman(meetingMoid, mt)
			} else {
				Confirm(t('若要重置管理方，您将失去管理方权限'), () => fetchSetChairman(meetingMoid, mt))
			}
		}
	})
	const handleDropSpeaker = useLock(async (dataTransfer: DropData) => {
		if (dataTransfer && dataTransfer.data && dataTransfer.data.mt) {
			let mt = dataTransfer.data.mt
			if (speaker) {
				if (mt.mt_key === speaker.mtKey) {
					return
				}
			}
			if (mt.mt_key === '0.0.0.0_0') {
				return
			}
			if (usePlayVideoStore.getState().info.state !== 0) {
				Alert(t('会议放像过程中不能设置发言方'))
				return
			}
			if (usePlayVideoStore.getState().info.state === 1) {
				Alert(t('会议放像暂停后不能设置发言方'))
				return
			}
			await fetchSetSpeaker(meetingMoid, mt)
		}
	})
	const getChairManDataTransfer = (chairman: Mt) => {
		return {
			data: {
				mt: revert_mt(chairman),
				chairman: {},
			},
			from: 'chairman',
			...useMonitorStore.getState().nativeMonitorDropParse(chairman),
			// ...rxMainOut.getValue.nativeMonitor(chairman),
		}
	}
	const getSpeakerDataTransfer = (speaker: Mt | Meeting) => {
		return {
			data: {
				mt: speaker.isMt ? revert_mt(speaker) : revert_meeting(speaker),
				speaker: {},
			},
			from: 'speaker',
			...useMonitorStore.getState().nativeMonitorDropParse(speaker),
			// ...rxMainOut.getValue.nativeMonitor(speaker),
		}
	}
	return (
		<Wrap>
			<DragDropContextProvider>
				<Droppable onDrop={handleDropChairman} isPlaceholder={false}>
					{(setDroppableRef) => (
						<ManagerWrap ref={setDroppableRef}>
							{chairman ? (
								<Draggable
									dataTransfer={() => getChairManDataTransfer(chairman)}
									ghostRender={<ListItemGhost data={chairman} />}
								>
									<div className="manager-wrap__top">
										<IconChairmanAvatar
											hasChairman={true}
											isOnline={chairman.status.isOnline}
											className="manager-avatar"
										/>
										<ManagerChairmanIcons chairman={chairman} />
									</div>
									<div className="manager-name" title={chairman.name}>
										{chairman.name}
									</div>
								</Draggable>
							) : (
								<>
									<div className="manager-wrap__top">
										<IconChairmanAvatar
											hasChairman={false}
											isOnline={false}
											className="manager-avatar"
										/>
										<span className="no-action-tips">{t('管理方')}</span>
									</div>
									<div className="no-name-tips">{t('请拖拽与会方至此位置')}</div>
								</>
							)}
						</ManagerWrap>
					)}
				</Droppable>
				<Droppable onDrop={handleDropSpeaker} isPlaceholder={false}>
					{(setDroppableRef) => (
						<ManagerWrap ref={setDroppableRef}>
							{speaker ? (
								<Draggable
									dataTransfer={() => getSpeakerDataTransfer(speaker)}
									ghostRender={<ListItemGhost data={speaker} />}
								>
									<div className="manager-wrap__top">
										<IconSpeakerAvatar
											hasSpeaker={true}
											isOnline={speaker.status.isOnline}
											className="manager-avatar"
										/>
										<ManagerSpeakerIcons speaker={speaker} />
									</div>
									<div className="manager-name" title={speaker.name}>
										{speaker.name}
									</div>
								</Draggable>
							) : (
								<>
									<div className="manager-wrap__top">
										<IconSpeakerAvatar
											hasSpeaker={false}
											isOnline={false}
											className="manager-avatar"
										/>
										<span className="no-action-tips">{t('发言方')}</span>
									</div>
									<div className="no-name-tips">{t('请拖拽与会方至此位置')}</div>
								</>
							)}
						</ManagerWrap>
					)}
				</Droppable>
			</DragDropContextProvider>
		</Wrap>
	)
}
